import userInfo from "./userInfo.js"
const state = { // 全局参数的初始状态
	websocketKey: '',
	socket_flag: false,
	socketTask: null,
	that: null,
	message: null,
	data: null,
	driverOrder: {},
}
const mutations = { // 更新全局状态
	WEBSOCKET_INIT(state, url) {
		state.socketTask = uni.connectSocket({
			url, // url是websocket连接ip
			success() {
				state.socket_flag = true;
			}
		})
		state.socketTask.onOpen((res) => {
			// 注：只有连接正常打开中 ，才能正常收到消息
			state.socketTask.onMessage(res => {
				// console.log('收到服务器内容：' + res.data)
				let data = JSON.parse(res.data);
				console.log('收到服务器内容：' + data)
				console.log(data)
				/**
				 * 判断后端推送的业务类型
				 * data.messageType：1 
				 * data.messageType：2
				 * data.messageType：3 接收运输订单
				 * data.messageType：4 接受退货订单
				 * data.messageType：5 接收排队信息
				 *  .......
				 * 
				 * */
				if (data.messageType == 1) {
					let that = state.that
					state.websocketKey = data.messageContent;
					//获得车牌号
					var carNumber = uni.getStorageSync('userName');
					//内容 messageType 1是系统消息和登录有关
					let message = "{'messageContent': '" + state.websocketKey + ":" + carNumber +
						"','messageType': 1,'receivePerson': 'app','sendPerson': 'self'}";
					//发送消息 
					console.log(message)
					this.commit("WEBSOCKET_SEND", message);
				} else if (data.messageType == 2) {
					// 暂未定义
				} else if (data.messageType == 3) {
					// 将后端推送的信息存放到
					userInfo.mutations.SET_MESSAGECONTENT(userInfo.state, data.messageContent);
				} else if (data.messageType == 4) {
					// 将后端推送的信息存放到
					userInfo.mutations.SET_OUTMESSAGECONTENT(userInfo.state, data.messageContent);
				} else if (data.messageType == 5) {
					userInfo.mutations.SET_QUEUEMESSAGECONTENT(userInfo.state, data.messageContent);
				}
			});
		})
	},
	WEBSOCKET_SEND(state, data) {
		state.socketTask.send({
			data,
			async success() {},
		})
	},
	SET_DRIVERORDER(state, val) {
		state.driverOrder = val;
	},
	SET_THAT(state, data) {
		state.that = data;
	},
	CLOSE_SOCKET(state) {
		if (!state.socketTask) return
		state.socketTask.close({
			success(res) {
				state.socket_flag = false;
			},
			fail(err) {
				console.log('关闭失败', err)
			}
		})
	}
}
const getters = {
	GET_WEBSOCKET_KEY(state) {
		//console.log('state.businessInfo',state.businessInfo);
		return state.websocketKey;
	},
}
const actions = { // 可以不设置触发动作
	WEBSOCKET_INIT({
		commit
	}, url) {
		commit('WEBSOCKET_INIT', url)
	},
	WEBSOCKET_SEND({
		commit
	}, data) {
		commit('WEBSOCKET_SEND', data)
	},
	CLOSE_SOCKET({
		commit
	}) {
		commit('CLOSE_SOCKET')
	}

}

export default {
	state,
	getters,
	mutations,
	actions
}